package com.module.dialog;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;

import com.module.dialog.adapter.CustomAdapter;
import com.module.dialog.inter.DialogOnItemListener;

import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Author: deng
 * Date: 2020/10/20
 * Description: 自定义对话框-自定义列表adapter
 */
public class CustomListDialog<T> extends BaseBuilder<CustomListDialog<T>> implements DialogOnItemListener {
    RecyclerView recyclerView; //列表控件
    ListParam<T> mListParam; //列表参数

    public CustomListDialog(Context context) {
        super(context);
    }

    @Override
    public CustomListDialog getBuilder() {
        return this;
    }

    /**
     * 初始化控件
     */
    @Override
    public void initContentView() {
        mListParam = new ListParam();
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_list, null);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        setContentView(view);
    }

    @Override
    protected void connectView() {
    }

    public CustomListDialog<T> setAdapter(CustomAdapter<T> adapter) {
        mListParam.adapter = adapter;
        mListParam.adapter.setOnItemListener(this);
        mListParam.adapter.setListParam(mListParam);
        recyclerView.setAdapter(mListParam.adapter);
        return this;
    }

    public CustomListDialog<T> setItems(List<T> items) {
        mListParam.items = items;
        mListParam.adapter.notifyDataSetChanged();
        return this;
    }

    public CustomListDialog<T> setDialogOnItemListener(DialogOnItemListener onItemListener) {
        mListParam.onItemListener = onItemListener;
        return this;
    }

    public CustomListDialog<T> setCallBack(DialogCallBack listener) {
        mListParam.callBackListener = listener;
        return this;
    }


    @Override
    public void onItemClick(int position) {
        if (mListParam.onItemListener != null) {
            mListParam.onItemListener.onItemClick(position);
        }
    }


    /**
     * 重写按钮点击事件
     */
    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (mListParam.callBackListener != null) {
            int tag = Integer.parseInt(v.getTag().toString());
            mListParam.callBackListener.callback(tag);
        }
    }

    /**
     * 列表参数
     */
    public class ListParam<T> {
        public CustomAdapter<T> adapter;
        public List<T> items;
        public DialogOnItemListener onItemListener;
        public DialogCallBack callBackListener;
    }

    public interface DialogCallBack {
        void callback(int which);
    }


}